//
//  AY_BookDPage.m
//  AiYue
//
//  Created by boWen on 2023/11/21.
//

#import "AY_BookDPage.h"
#import "AY_BookDHeaderView.h"
#import "AY_BookDCell.h"
#import "AY_BookDCell2.h"
#import "AY_BookPChasePage1.h"
#import "AY_UseListPage.h"
#import <WebKit/WebKit.h>
@interface AY_BookDPage ()<UITableViewDelegate, UITableViewDataSource, WKUIDelegate, WKNavigationDelegate, SXBookDCellDelegate>
@property (nonatomic, strong) UITableView * baseTableView;
@property (nonatomic, strong) NSArray * productList;
@property (nonatomic, strong) AY_BookDHeaderView * sdHeaderView;
@property (nonatomic, strong) NSArray * chaseList;
@property (nonatomic, strong) VpProductModel * currModel;
@property(nonatomic,strong) WKWebView * webView;
@property (nonatomic, strong) NSString * h5Refer;
@property (nonatomic, strong) ConfigModel *configModel;
@property (nonatomic, strong) UserInfo * infoModel;
@property (nonatomic, strong) NSString *pType;
@end

@implementation AY_BookDPage

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self barStyleLight];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self barStyleBlack];
    [[NSNotificationCenter defaultCenter] postNotificationName:ZFREFRESH object:nil];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    AY_BookDCell *cell = [self.baseTableView cellForRowAtIndexPath:indexPath];
    cell.timer = nil;
    [cell.timer invalidate];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.pType = @"ZFB";
    [self initWithNav];
    [self getConfigWithNet];
    [self infoModel];
    [self loadData];
    self.view.backgroundColor = [UIColor whiteColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:ZFREFRESH object:nil];
}

- (void)refresh {
    [self getConfigWithNet];
    [self loadData];
}

- (void)loadData {
    [AYApiRequest getUserInfoSuccess:^(AY_UserModel * _Nonnull pkg) {
        if([pkg.code isEqualToString:@"200"]) {
            self.infoModel = pkg.data;
            self.sdHeaderView.infoModel = self.infoModel;
        }
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
        
}

- (void)initWithNav {
    self.gk_navTitle = @"书豆";
    self.gk_navTitleColor = COLOR(@"#ffffff");
    self.gk_navBackgroundColor = THEME_COLOR;
    self.gk_navLeftBarButtonItem = [UIBarButtonItem itemWithImageName:@"AY_nav_pop_w" target:self action:@selector(popVC)];
    
    UIButton *xfBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [xfBtn setTitle:@"消费记录  " forState:UIControlStateNormal];
    [xfBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [xfBtn addTarget:self action:@selector(shudouList) forControlEvents:UIControlEventTouchUpInside];
    xfBtn.titleLabel.font = YFont(14);
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:xfBtn];
    self.gk_navRightBarButtonItem = item;
    
    self.gk_navItemRightSpace = YNUM(12);
    [self setupHeaderView];
    [self.view addSubview:self.baseTableView];
}

- (void)shudouList {
    AY_UseListPage * page = [[AY_UseListPage alloc] init];
    page.logType = consumptionLog_bookBean;
    [self.navigationController pushViewController:page animated:YES];
}


-(void)popVC{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)getConfigWithNet {
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [AYApiRequest getPackageProductListWithAssetType:@"1" Success:^(AY_BookVpModel * _Nonnull pkg) {
        dispatch_group_leave(group);
        if([pkg.code isEqualToString:@"200"]) {
            self.productList = pkg.data;
            if(self.productList.count > 0 ) {
//                self.myHeaderView.vpModel = self.productList[0];
//                self.myFooterView.vpModel = self.productList[0];
            }
        }
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_enter(group);
    [AYApiRequest getPackagePymentTypeListSuccess:^(AY_PyChaseModel * _Nonnull pkg) {
        dispatch_group_leave(group);
        if([pkg.code isEqualToString:@"200"]) {
            self.chaseList = pkg.data;
        }
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];
    
    dispatch_group_enter(group);
    [AYApiRequest APPConfigSuccess:^(AY_ConfigModel * _Nonnull pkg) {
        self.configModel = pkg.data;
        dispatch_group_leave(group);
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
    }];

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self.baseTableView reloadData];
    });
      
}


- (UITableView *)baseTableView {
    if (!_baseTableView) {
        UITableView * myTableView = [AYTool creatMyTableView:CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, GK_SCREEN_WIDTH, GK_SCREEN_HEIGHT - GK_STATUSBAR_NAVBAR_HEIGHT)];
        myTableView.delegate = self;
        myTableView.dataSource = self;
        myTableView.tableHeaderView = self.sdHeaderView;
        [myTableView registerClass:[AY_BookDCell class] forCellReuseIdentifier:@"AY_BookDCell"];
        [myTableView registerClass:[AY_BookDCell2 class] forCellReuseIdentifier:@"AY_BookDCell2"];
        myTableView.backgroundColor = [UIColor clearColor];
        _baseTableView = myTableView;
    }
    return _baseTableView;
}

- (NSArray *)productList {
    if(!_productList) {
        _productList = [NSArray array];
    }
    return _productList;
}

- (NSArray *)chaseList {
    if(!_chaseList) {
        _chaseList = [NSArray array];
    }
    return _chaseList;
}

- (AY_BookDHeaderView *)sdHeaderView {
    if(!_sdHeaderView) {
        _sdHeaderView = [[AY_BookDHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, YNUM(104))];
    }
    return _sdHeaderView;;
}

#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == 0) {
        AY_BookDCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AY_BookDCell"];
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
        [cell sendVpDataAry:self.productList andPType:self.pType];
        cell.delegate = self;
        Weak_Self
        cell.bookDBlock = ^(NSInteger indx) {
            if(weakSelf.productList.count > indx) {
                VpProductModel * sdModel = weakSelf.productList[indx];
                weakSelf.currModel = sdModel;
            }
        };
        cell.dPyBlock = ^{
            [weakSelf pyChaseBookDWithAction];
        };
        return cell;
    }else {
        AY_BookDCell2 * cell = [tableView dequeueReusableCellWithIdentifier:@"AY_BookDCell2"];
        cell.model = self.configModel;
        return cell;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == 0) {
        return YNUM(288);
    }else{
        return [self.baseTableView fd_heightForCellWithIdentifier:@"AY_BookDCell2" configuration:^(id cell) {
            [self setupOfCell:cell atIndexPath:indexPath];
        }];
    }
}

- (void)setupOfCell:(AY_BookDCell2 *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.model = self.configModel;
}

- (void)setupHeaderView {
    UIView * bgView;
    bgView = [AYTool createViewWithFrame:CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, GK_SCREEN_WIDTH, YNUM(250)) andBg:THEME_COLOR andRadius:0.0 andAddSubView:self.view];
}


- (void)pyChaseBookDWithAction {
    NSMutableArray * dataArry = [NSMutableArray array];
    if (self.chaseList.count > 0) {
        for (ChaseModel * model in self.chaseList) {
            NSMutableDictionary * paramDic = [NSMutableDictionary dictionary];
            [paramDic setValue:kStringUtils(model.typeName) forKey:@"typeName"];
            [paramDic setValue:kStringUtils(model.typeCoverUrl) forKey:@"typeCoverUrl"];
            [paramDic setValue:kStringUtils(model.typeCode) forKey:@"type"];
            [dataArry addObject:paramDic];
        }
    }
    AY_BookPChasePage1 *pop = [[AY_BookPChasePage1 alloc]initTotalPy:self.currModel.price vc:self dataSource:dataArry andPtype:self.pType andInfo:self.currModel];
    STPopupController *popVericodeController = [[STPopupController alloc] initWithRootViewController:pop];
    popVericodeController.style = STPopupStyleBottomSheet;
    [popVericodeController presentInViewController:self];

    pop.pyType = ^(NSString *type,NSString *balance) {
        self.pType = type;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        AY_BookDCell *cell = [self.baseTableView cellForRowAtIndexPath:indexPath];
        [cell sendVpDataAry:self.productList andPType:self.pType];
    };
}

- (void)ktAction {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    AY_BookDCell *cell = [self.baseTableView cellForRowAtIndexPath:indexPath];
    cell.surePyBtn.hidden = YES;
    cell.loadingBack.hidden = NO;
    [AYApiRequest createOrdeWithPymentType:self.pType productId:self.currModel.vpId productName:self.currModel.productName articleId:self.bookId Success:^(AY_SignModel * _Nonnull pkg) {
        if ([pkg.code isEqual:@"200"]) {
            SignOwnModel *model = pkg.data;
            [self loadWebViewWithUrl:model.thirdOrderData withRechargeType:self.pType andModel:model];
        }else {
            cell.surePyBtn.hidden = NO;
            cell.loadingBack.hidden = YES;
            ShowToast(pkg.msg);
        }
        
    } failure:^(int status, NSString * _Nonnull info) {
        cell.surePyBtn.hidden = NO;
        cell.loadingBack.hidden = YES;
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

- (void)loadWebViewWithUrl:(NSString *)url withRechargeType:(NSString *)rechargeType andModel:(SignOwnModel *)model {
    _webView = [[WKWebView alloc]initWithFrame:CGRectZero];
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    self.h5Refer = model.h5Refer;
    if ([rechargeType isEqual:@"WX"]) {
        NSMutableURLRequest * request  = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
        [request setValue:[self getRefer] forHTTPHeaderField:@"Referer"];
        [_webView loadRequest:request];
    }else {
        [_webView loadHTMLString:url baseURL:nil];
    }
    [self.view addSubview:_webView];
}

- (NSString *)getRefer {
    if ([self.h5Refer rangeOfString:@"https://"].location != NSNotFound) {
        NSString *refresh = [NSString stringWithFormat:@"%@://",[self.h5Refer stringByReplacingOccurrencesOfString:@"https://" withString:@"www."]];
        return [NSString stringWithFormat:@"%@://",refresh];
    }else if ([self.h5Refer rangeOfString:@"http://"].location != NSNotFound) {
        NSString *refresh = [NSString stringWithFormat:@"%@://",[self.h5Refer stringByReplacingOccurrencesOfString:@"http://" withString:@"www."]];
        return [NSString stringWithFormat:@"%@://",refresh];
    }else {
        return self.h5Refer;
    }
}

#pragma mark - WebViewDelegate
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"111>>>>>加载完成");
}

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSURL *URL = navigationAction.request.URL;
    NSString * urlStr = URL.absoluteString;
    NSString * idStr = [AYMMKV getStringForKey:AP];
    idStr = [idStr stringByAppendingString:@"://"];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    AY_BookDCell *cell = [self.baseTableView cellForRowAtIndexPath:indexPath];
    
    if ([urlStr containsString:idStr]) {
        NSString * resultUrl = [self URLDecodedString:urlStr];
        NSString* dataStr = [resultUrl substringFromIndex:23];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[dataStr dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
        NSMutableDictionary * mutDict = [[NSMutableDictionary alloc]initWithDictionary:dict];
        [mutDict setObject:SXAPPBUNDLEID forKey:@"fromAppUrlScheme"];
        NSString * dictStr = [self arrayToJSONString:mutDict];
        NSString * ecodeUrl = [self URLEncodedStringWithUrl:dictStr];
        NSString * resultStr = [NSString stringWithFormat:@"%@://%@client/?%@",[AYMMKV getStringForKey:AP],[AYMMKV getStringForKey:AP],ecodeUrl];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:resultStr] options:@{} completionHandler:nil];

//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:resultStr]];
        decisionHandler(WKNavigationActionPolicyCancel);
        cell.surePyBtn.hidden = NO;
        cell.loadingBack.hidden = YES;
        return;
    }else if([urlStr containsString:[NSString stringWithFormat:@"%@://",[AYMMKV getStringForKey:WX]]]) {
        if (![urlStr containsString:@"redirect_url="]) {
            NSString * redirect = [NSString stringWithFormat:@"&redirect_url=%@",self.h5Refer];
            urlStr = [urlStr stringByAppendingString:redirect];
        }
        NSURL * url = [NSURL URLWithString:urlStr];
        NSLog(@"%@",url);
//        [[UIApplication sharedApplication] openURL:url];
        
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];

        decisionHandler(WKNavigationActionPolicyCancel);
        cell.surePyBtn.hidden = NO;
        cell.loadingBack.hidden = YES;
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (NSString *)URLDecodedString:(NSString *)url
{
    NSString *decodedString  = ( NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                      (__bridge CFStringRef)url,
                                                                                                                      CFSTR(""),
                                                                                                                      CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)));
    return decodedString;
}

- (NSString *)arrayToJSONString:(id)object
{
    NSError *error = nil;
    if (object == nil) {
        return @"";
    }else {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return jsonString;
    }
}

- (NSString *)URLEncodedStringWithUrl:(NSString* )url {
    
    NSString *encodedString = (NSString* )CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)url,NULL,(CFStringRef) @"!'();:@&+$,%#[]|",kCFStringEncodingUTF8));
    
    return encodedString;
}
@end
